package org.monitor.controller.malog;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.monitor.http.RestResult;
import org.monitor.kit.FileKit;
import org.monitor.model.MonitorStateManager;
import org.monitor.servlet.controller.Controller;

/**
 * 日志
 * @author zhaojjd
 *
 */
public class MALogController extends Controller {

	public void list(){
		getPairs().checkRequired("ip", "port", "monitor");
		
		String ip = getPair("ip");
		String port = getPair("port");
		String monitor = getPair("monitor");
		
		List<String> list = new ArrayList<String>();
		String storeDir = MonitorStateManager.getServerInstance().getMonitorDir(ip, port, monitor).toString();
		File dir = new File(storeDir);
		if(dir.exists()){
			File[] files = dir.listFiles();
			for (File file : files) {
				list.add(file.getName());
				
			}
			Collections.sort(list, new Comparator<String>(){
				@Override
				public int compare(String preName, String nextName) {
					return -1 * preName.compareTo(nextName);
				}
			});
		}
		
		boolean monitoring = MonitorStateManager.getServerInstance().hasMonitoring(ip, port, monitor);
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("monitoring", monitoring);
		data.put("logs", list);
		
		RestResult rst = new RestResult();
		rst.setData(data);
		renderJson(rst);
	}
	
	public void get(){
		getPairs().checkRequired("ip", "port", "monitor", "name");
		
		String ip = getPair("ip");
		String port = getPair("port");
		String monitor = getPair("monitor");
		String name = getPair("name");
		
		String filename = MonitorStateManager.getServerInstance().getMonitorDir(ip, port, monitor).append(name).toString();
		File file = new File(filename);
		
		RestResult rst = new RestResult();
		
		String content = FileKit.read(file, "UTF-8");
		rst.setData(content);
		renderJson(rst);
	}
	
	public void del(){
		getPairs().checkRequired("ip", "port", "monitor", "name");
		
		String ip = getPair("ip");
		String port = getPair("port");
		String monitor = getPair("monitor");
		String name = getPair("name");
		
		String filename = MonitorStateManager.getServerInstance().getMonitorDir(ip, port, monitor).append(name).toString();
		File file = new File(filename);
		
		RestResult rst = new RestResult();
		
		boolean flag = FileKit.deleteAll(file);
		if(!flag){
			rst.setState(-1);
			rst.setMsg("删除失败！");
		}
		renderJson(rst);
	}

}
